package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.Type;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.Doc;
import com.ruoyi.system.service.IDocService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TypeMapper;
import com.ruoyi.common.core.domain.entity.Type;
import com.ruoyi.system.service.ITypeService;

/**
 * 组卷类别Service业务层处理
 * 
 * @author tq
 * @date 2025-04-19
 */
@Service
public class TypeServiceImpl implements ITypeService 
{
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private IDocService docService;

    /**
     * 查询组卷类别
     * 
     * @param typeId 组卷类别主键
     * @return 组卷类别
     */
    @Override
    public Type selectTypeByTypeId(Long typeId)
    {
        return typeMapper.selectTypeByTypeId(typeId);
    }

    /**
     * 查询组卷类别列表
     * 
     * @param type 组卷类别
     * @return 组卷类别
     */
    @Override
    public List<Type> selectTypeList(Type type)
    {
        return typeMapper.selectTypeList(type);
    }

    /**
     * 新增组卷类别
     * 
     * @param type 组卷类别
     * @return 结果
     */
    @Override
    public int insertType(Type type)
    {
        if(null!=type.getParentId()){
            Type info = typeMapper.selectTypeByTypeId(type.getParentId());
            if(null!=info&& StringUtils.isNotBlank(info.getAncestors())){
                type.setAncestors(info.getAncestors() + "," + type.getParentId());
            }else {
                type.setAncestors(type.getParentId().toString());
            }
        }
        type.setCreateTime(DateUtils.getNowDate());
        return typeMapper.insertType(type);
    }

    /**
     * 修改组卷类别
     * 
     * @param type 组卷类别
     * @return 结果
     */
    @Override
    public int updateType(Type type)
    {   Type newParentType = typeMapper.selectTypeByTypeId(type.getParentId());
        Type oldType = typeMapper.selectTypeByTypeId(type.getTypeId());
        if (StringUtils.isNotNull(newParentType) && StringUtils.isNotNull(oldType))
        {
            String newAncestors = newParentType.getAncestors() + "," + newParentType.getTypeId();
            String oldAncestors = oldType.getAncestors();
            type.setAncestors(newAncestors);
            updateChildren(type.getTypeId(), newAncestors, oldAncestors);
        }
        type.setUpdateTime(DateUtils.getNowDate());
        return typeMapper.updateType(type);
    }

    private void updateChildren(Long typeId, String newAncestors, String oldAncestors) {
        List<Type> children = typeMapper.selectChildrenDeptById(typeId);
        for (Type child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            typeMapper.updateDeptChildren(children);
        }
    }

    /**
     * 批量删除组卷类别
     * 
     * @param typeIds 需要删除的组卷类别主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteTypeByTypeIds(Long[] typeIds)
    {
        if(typeIds!=null&&typeIds.length>0){
            List<Doc> docs = docService.selectDocByTypeIds(typeIds);
            if(docs!=null&& !docs.isEmpty()){
                return AjaxResult.error("删除失败，存在文档关联卷组");
            }
        }
        typeMapper.deleteTypeByTypeIds(typeIds);
        return AjaxResult.success("删除成功");
    }

    /**
     * 删除组卷类别信息
     * 
     * @param typeId 组卷类别主键
     * @return 结果
     */
    @Override
    public int deleteTypeByTypeId(Long typeId)
    {
        return typeMapper.deleteTypeByTypeId(typeId);
    }

    @Override
    public boolean checkTypeNameUnique(Type type) {
        Long typeId = StringUtils.isNull(type.getTypeId()) ? -1L : type.getTypeId();
        Type info = typeMapper.checkNameUnique(type.getName(), type.getParentId());
        if (StringUtils.isNotNull(info) && info.getTypeId().longValue() != typeId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public List<TreeSelect> selectTreeList(Type type) {
        List<Type> types = SpringUtils.getAopProxy(this).selectTypeList(type);
        return buildTreeSelect(types);
    }

    private List<TreeSelect> buildTreeSelect(List<Type> types) {
        List<Type> typeTrees = buildTypeTree(types);
        return typeTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    private List<Type> buildTypeTree(List<Type> types) {
        List<Type> returnList = new ArrayList<Type>();
        List<Long> tempList = types.stream().map(Type::getTypeId).collect(Collectors.toList());
        for (Type type : types)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(type.getParentId()))
            {
                recursionFn(types, type);
                returnList.add(type);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = types;
        }
        return returnList;
    }

    private void recursionFn(List<Type> list, Type t) {
        // 得到子节点列表
        List<Type> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Type tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private boolean hasChild(List<Type> list, Type t) {
        return getChildList(list, t).size() > 0;
    }

    private List<Type> getChildList(List<Type> list, Type t) {
        List<Type> tlist = new ArrayList<Type>();
        Iterator<Type> it = list.iterator();
        while (it.hasNext())
        {
            Type n = (Type) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getTypeId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
